package com.changwu.cwbase.AppTest.DesignPattern;

/**
 * Created by changwu on 2018/10/14.
 */
public class StrategyDesign {
    public interface MemberStrategy {
        /**
         * 计算图书的价格
         * @param booksPrice    图书的原价
         * @return    计算出打折后的价格
         */
        double calcPrice(double booksPrice);
    }
    public static class PrimaryMemberStrategy implements MemberStrategy{
        /**
         * 初级会员折扣
         */
        @Override
        public double calcPrice(double booksPrice) {
            System.out.println("对于初级会员的没有折扣");
            return booksPrice;
        }
    }
    public static class IntermediateMemberStrategy implements MemberStrategy{
        /**
         * 中级会员折扣
         */
        @Override
        public double calcPrice(double booksPrice) {
            System.out.println("对于中级会员的折扣为10%");
            return booksPrice * 0.9;
        }
    }
    public static class AdvancedMemberStrategy implements MemberStrategy{
        /**
         * 高级会员折扣
         */
        @Override
        public double calcPrice(double booksPrice) {
            System.out.println("对于高级会员的折扣为20%");
            return booksPrice * 0.8;
        }
    }
    public static class Price {
        //持有一个具体的策略对象
        private MemberStrategy strategy;
        /**
         * 构造函数，传入一个具体的策略对象
         */
        public <T extends MemberStrategy> Price(Class<T> clz){
            MemberStrategy strategy = null;
            try {
                strategy = (MemberStrategy) Class.forName(clz.getName()).newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.strategy = strategy;
        }

        /**
         * 计算图书的价格
         * @param booksPrice    图书的原价
         * @return    计算出打折后的价格
         */
        public double quote(double booksPrice){
            return this.strategy.calcPrice(booksPrice);
        }
    }
    public void testStrategyDesign(){
        //创建环境
        Price price = new Price(AdvancedMemberStrategy.class);
        //计算价格
        double quote = price.quote(300);
        System.out.println("图书的最终价格为：" + quote);
    }
}
